part of 'index.dart';

class AgManager {
  AgManager._();
  static final AgManager of = AgManager._();
  final engine = createAgoraRtcEngine();

  final _remoteStreamController = StreamController<bool>.broadcast();
  Stream<bool> get remoteStream => _remoteStreamController.stream;

  Future<void> init({
    VoidCallback? onSuccess,
    VoidCallback? onError,
  }) async {
    try {
      await engine.initialize(const RtcEngineContext(
        appId: '86b2ac3562e343f5af1acd303e188c6c',
        channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,
      ));
      //engine.registerEventHandler(_eventHandler());
      debugPrint("==声网ag==:声网引擎初始化成功");
      onSuccess?.call();
    } catch (err) {
      debugPrint("==声网ag==:声网引擎初始化失败");
      onError?.call();
    }
  }

  Future<bool> joinChannel({
    required String token,
    required String channelId,
    required int uid,
  }) async {
    try {
      await engine.joinChannel(
        token: token,
        channelId: channelId,
        options: const ChannelMediaOptions(
          // 自动订阅所有音频流
          autoSubscribeAudio: true,
          // 发布麦克风采集的音频
          publishMicrophoneTrack: true,
          // 设置用户角色为 clientRoleBroadcaster（主播）或 clientRoleAudience（观众）
          clientRoleType: ClientRoleType.clientRoleBroadcaster,
        ),
        // uid 为 0 表示引擎内部随机生成用户名
        uid: uid,
      );
      debugPrint("==声网ag==:加入频道$channelId成功");
      return true;
    } catch (err) {
      debugPrint("==声网ag==:加入频道$channelId失败 reson:${err.toString()}");
      return false;
    }
  }

  // RtcEngineEventHandler _eventHandler() {
  //   return RtcEngineEventHandler(
  //     // 成功加入频道回调
  //     onJoinChannelSuccess: (RtcConnection connection, int elapsed) {
  //       debugPrint("==声网==:成功加入频道回调local user ${connection.localUid} joined");
  //     },
  //     // 远端用户或主播加入当前频道回调
  //     onUserJoined: (RtcConnection connection, int remoteUid, int elapsed) {
  //       debugPrint("==声网==:远端用户或主播加入当前频道回调remote user $remoteUid joined");
  //       _remoteStreamController.add(true);
  //     },
  //     // 远端用户或主播离开当前频道回调
  //     onUserOffline: (
  //       RtcConnection connection,
  //       int remoteUid,
  //       UserOfflineReasonType reason,
  //     ) {
  //       debugPrint("==声网==:远端用户或主播离开当前频道回调remote user $remoteUid left channel");
  //       _remoteStreamController.add(false);
  //     },
  //   );
  // }

  Future<void> leaveChannel() async {
    await engine.leaveChannel();
    await engine.release();
    debugPrint("==声网ag==:当前用户离开频道");
  }
}
